package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Expense;
import cn.wolfcode.trip.base.domain.InsuranceOrder;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.ExpenseMapper;
import cn.wolfcode.trip.base.mapper.InsuranceOrderMapper;
import cn.wolfcode.trip.base.mapper.UserMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IInsuranceOrderService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class InsuranceOrderServiceImpl implements IInsuranceOrderService {
    @Autowired
    InsuranceOrderMapper insuranceOrderMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    private ExpenseMapper expenseMapper;


    @Override
    public void save(InsuranceOrder insuranceOrder, Long userId) {
        // 1、判断余额是否充足：查询用户余额
        User user = userMapper.selectByPrimaryKey(userId);
        Double residual = user.getBalance();// 用户余额

        Expense e = new Expense();//消费记录

        double orderAccount = insuranceOrder.getOrderAmount().doubleValue();// 产品价格

        // 2、根据余额是否充足判断结果，作出不同处理
        if (residual >= orderAccount) {
            // 2-1 余额充足时，直接扣款，保存订单
            double balance = residual - orderAccount;
            user.setBalance(balance);
            // 从用户钱包中扣款支付
            userMapper.chargeForOrder(user);

            // 2-2 创建下订单时间，保存订单
            insuranceOrder.setOrderTime(new Date());
            insuranceOrderMapper.insert(insuranceOrder);

            // 2-3 消费记录保存
            e.setConsumeMoney(orderAccount);
            e.setConsumeName(insuranceOrder.getProductName());
            e.setConsumeTime(new Date());
            e.setUser(user);
            e.setConsumeType("保险");
            expenseMapper.insert(e);

        } else {

            // 2-2 余额不足时，抛出运行时异常，提醒用户可用余额不足
            throw new RuntimeException("您的余额不足，请充值！");

        }

    }

    @Override
    public PageInfo queryForOrders(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrderBy());
        List<?> list = insuranceOrderMapper.selectForList(qo);
        return new PageInfo<>(list);
    }


}